<?php

namespace app\common\library;

use think\Log;
use think\Env;
use think\Exception;
use app\admin\model\pt\Depart as DepartModel;
use app\admin\model\pt\Job as JobModel;
use app\admin\model\pt\Person as PersonModel;
use app\admin\model\pt\DutyList as DutyModel;
use app\admin\model\pt\LaborLog as LaborLogModel;
use app\admin\model\Admin as AdminModel;
use app\common\library\Plan as PlanLib;
use app\common\library\Salary as SalaryLib;
use app\admin\library\Auth;


class Duty
{
    protected $_departModel = null;
    protected $_jobModel = null;
    protected $_personModel = null;
    protected $_dutyModel = null;
    protected $_planLib = null;
    protected $_salaryLib = null;

    public function __construct()
    {
        $this->_departModel = new DepartModel();
        $this->_jobModel = new JobModel();
        $this->_personModel = new PersonModel();
        $this->_dutyModel= new DutyModel();
        $this->_planLib = new PlanLib();
        $this->_salaryLib = new SalaryLib();
    }

    public function batchHandleDuty($startDate, $endDate, $personId, $departId, $jobId)
    {
        $personInfo = $this->_personModel->get($personId);
        if (!$personInfo) {
            throw new Exception('人员信息未找到, id =>' . $personId);
        }
        $jobInfo = $this->_jobModel->where('id', $jobId)->find();
        if (!$jobInfo) {
            throw new Exception('岗位信息未找到, id =>' . $jobId);
        }
        if ($jobInfo->status != 'normal') {
            throw new Exception('岗位信息已隐藏, id =>' . $jobId . ', status =>' . $jobInfo->status);
        }
        $departInfo = $this->_departModel->where('id', $departId)->find();
        if (!$departInfo) {
            throw new Exception('部门信息未找到, id =>' . $departId);
        }
        if ($departInfo->status != 'normal') {
            throw new Exception('部门信息已隐藏, id =>' . $departId . ', status =>' . $departInfo->status);
        }
        $startDate = date('Ymd', strtotime($startDate));
        $endDate = date('Ymd', strtotime($endDate));
        for ($date = $startDate; $date <= $endDate; $date++)
        {
            $checkDate = date('Ymd', strtotime($date));
            if ($checkDate != $date) {
                continue;
            }
            $this->_planLib->checkJobPlan($jobInfo->id, $date);
            $this->saveDuty($personId, $jobInfo, $departInfo, $date);
            $this->calDutyTotal($jobId, $departId, $date);
        }
    }

    public function handleduty($date, $personId, $departId, $jobId)
    {
        $personInfo = $this->_personModel->get($personId);
        if (!$personInfo) {
            throw new Exception('人员信息未找到, id =>' . $personId);
        }
        $jobInfo = $this->_jobModel->where('id', $jobId)->find();
        if (!$jobInfo) {
            throw new Exception('岗位信息未找到, id =>' . $jobId);
        }
        if ($jobInfo->status != 'normal') {
            throw new Exception('岗位信息已隐藏, id =>' . $jobId . ', status =>' . $jobInfo->status);
        }
        $departInfo = $this->_departModel->where('id', $departId)->find();
        if (!$departInfo) {
            throw new Exception('部门信息未找到, id =>' . $departId);
        }
        if ($departInfo->status != 'normal') {
            throw new Exception('部门信息已隐藏, id =>' . $departId . ', status =>' . $departInfo->status);
        }
        $dateId = date('Ymd', strtotime($date));
        $this->_planLib->checkJobPlan($jobInfo->id, $date);
        $this->saveDuty($personId, $jobInfo, $departInfo, $dateId);
        $this->calDutyTotal($jobId, $departId, $dateId);
    }

    public function batchHandlePersonsDuty($startDate, $endDate, $personIds, $departId, $jobId)
    {
        $jobInfo = $this->_jobModel->where('id', $jobId)->find();
        if (!$jobInfo) {
            throw new Exception('岗位信息未找到, id =>' . $jobId);
        }
        if ($jobInfo->status != 'normal') {
            throw new Exception('岗位信息已隐藏, id =>' . $jobId . ', status =>' . $jobInfo->status);
        }
        $departInfo = $this->_departModel->where('id', $departId)->find();
        if (!$departInfo) {
            throw new Exception('部门信息未找到, id =>' . $departId);
        }
        if ($departInfo->status != 'normal') {
            throw new Exception('部门信息已隐藏, id =>' . $departId . ', status =>' . $departInfo->status);
        }
        $startDate = date('Ymd', strtotime($startDate));
        $endDate = date('Ymd', strtotime($endDate));
        for ($date = $startDate; $date <= $endDate; $date++) {
            $checkDate = date('Ymd', strtotime($date));
            if ($checkDate != $date) {
                continue;
            }
            $this->_planLib->checkJobPlan($jobInfo->id, $date, count($personIds));
        }
        foreach ($personIds as $personId) {
            for ($date = $startDate; $date <= $endDate; $date++) {
                $checkDate = date('Ymd', strtotime($date));
                if ($checkDate != $date) {
                    continue;
                }
                $this->saveDuty($personId, $jobInfo, $departInfo, $date);
            }
        }
        for ($date = $startDate; $date <= $endDate; $date++) {
            $checkDate = date('Ymd', strtotime($date));
            if ($checkDate != $date) {
                continue;
            }
            $this->calDutyTotal($jobId, $departId, $date);
        }
    }

    public function updateCurDuty($personInfo, $departId, $jobId, $jobDate, $dutyId = 0)
    {
        if (!is_object($personInfo))  {
            $personInfo = PersonModel::get($personInfo);
        }
        $curJobDate = $personInfo->job_date;
        $curJobId = $personInfo->pt_job_id;

        $personInfo->pt_depart_id = $departId; 
        $personInfo->pt_job_id = $jobId;
        $personInfo->job_date = $jobDate;
        $personInfo->save();
        if (!empty($jobId)) {
            // 增加薪酬基础表记录
            $this->_salaryLib->setObject($personInfo, null, null);
            $this->_salaryLib->addSalary($dutyId, $jobDate, 0, $jobId, $departId);
        } else {
            // 删除薪酬
            $this->_salaryLib->delSalary($personInfo->id, date('Ymd', strtotime($curJobDate)), $curJobId);
        }
    }

    public function calDutyTotal($jobId, $departId, $dateId)
    {
        $dutyTotal = $this->_dutyModel->where('pt_job_id', $jobId)
                                      ->where('date_id', $dateId)
                                      ->count();
        $this->_planLib->consumeJobPlan($jobId, $departId, $dateId, $dutyTotal);
    }

    public function handleLaborLog($person, $departId, $jobId, $dateId, $departName='', $jobName='', $action='add')
    {
        $laborId = 0;
        $personName = '';
        if (!is_object($person)) {
            $person = $this->_personModel->get($personId);
        }
        if ($person) {
            $personName = $person->user_name;
            $laborId = $person->pt_labor_id;
            $personId = $person->id;
        }
        if (empty($laborId)) {
            return;
        }
        if (empty($departName)){
            $depart = $this->_departModel->get($departId);
            if ($depart) {
                $departName = $depart->name;
            }
        }
        if (empty($jobName)){
            $job = $this->_jobModel->get($jobId);
            if ($job) {
                $jobName = $job->name;
            }
        }

        $auth = Auth::instance();
        $adminName = $auth->isLogin() ? $auth->username : __('Unknown');
        $adminId = $auth->isLogin() ? $auth->id : 0;

        $params = [];
        $params['labor_id'] = $laborId;
        $params['admin_name'] = $adminName;
        $params['admin_id'] = $adminId;
        $params['pt_depart_id'] = $departId;
        $params['depart_name'] = $departName;
        $params['pt_job_id'] = $jobId;
        $params['job_name'] = $jobName;
        $params['person_id'] = $personId;
        $params['person_name'] = $personName;
        $params['date_id'] = $dateId;
        $params['log_action'] = $action;
        $laborLog = new LaborLogModel(); 
        $laborLog->create($params);
    }


    private function saveDuty($personId, $jobInfo, $departInfo, $date)
    {
        $curDate = date('Ymd');
        $params = []; 
        $params['pt_person_id'] = $personId;
        $params['date_id'] = $date;
        $params['pt_depart_id'] = $departInfo->id;
        $params['depart_name'] = $departInfo->name;
        $params['pt_job_id'] = $jobInfo->id;
        $params['job_name'] = $jobInfo->name;
        $params['is_road'] = $jobInfo->is_road;
        $params['clock_lnglats'] = $jobInfo->clock_lnglats;
        $params['ignore_mins'] = $jobInfo->ignore_mins;
        // 查找日期小于当前日期的不做任何处理
        if ($date < $curDate) {
            Log::write('安排的工作日期小于当前日期, date_id =>' . $date);
            return;
        }
        // 查找有无对应日期的工作安排
        $dutyInfo = $this->_dutyModel->where('pt_person_id', $personId)->where('date_id', $date)->find();
        if (!$dutyInfo) {
            $dutyInfo = new DutyModel();
        } else {
            $params['id'] = $dutyInfo->id;
        }
        $dutyInfo->save($params);
        if ($date == $curDate) {
            $this->updateCurDuty($personId, $departInfo->id, $jobInfo->id, $date, $dutyInfo->id);
        }
        // 增加劳务公司人员的日志
        $person = $this->_personModel->get($personId);
        $this->handleLaborLog($person, $departInfo->id, $jobInfo->id, $date, $departInfo->name, $jobInfo->name);
    }

}
